import React from 'react';
import { connect } from 'react-redux'
import { messages, getToken } from "share/common";
import { Button } from "antd"
import Condition from 'components/condition'
import expenseReportService from 'containers/expense-report/expense-report.service'
const { If } = Condition;

class ButtonPrintCertificate extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      buttonVisible: false,
      link: ""
    }
  }

  componentDidMount() {
    const { appCode } = this.props;
    expenseReportService.getPrintCertificate(appCode).then(res => {
      if (res.data) {
        this.setState({ buttonVisible: true, link: res.data.link })
      }
    })
  }

  handleToPrint = () => {
    const { businessCode, parentBusinessCode, company } = this.props;
    let { link } = this.state;
    link += `&access_token=${JSON.parse(getToken()).access_token}`;
    let state = `businessCode=${businessCode}&companyOID=${company.companyOID}`;
    parentBusinessCode && (state += `&parentBusinessCode=${parentBusinessCode}`);
    link += `&state=${btoa(state)}`;
    window.open(link, '_blank')
  };

  render() {
    const { buttonVisible } = this.state;
    return (
      <If value={buttonVisible}>
        <Button type="primary"
                style={{marginLeft: 10}}
                onClick={this.handleToPrint}>{messages('expense-parent-report.key209')/*打印凭证*/}</Button>
      </If>
    )
  }
}

ButtonPrintCertificate.propTypes = {
  businessCode: React.PropTypes.string,
  parentBusinessCode: React.PropTypes.string,
  pageFrom: React.PropTypes.string,
  appCode: React.PropTypes.string
};

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default connect(mapStateToProps)(ButtonPrintCertificate)
